package com.freely.ui.listener;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Text;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.freely.R;
import com.freely.data.DateTest;
import com.freely.data.network.FreelyClient;
import com.freely.data.network.requestEntities.RQMemberInfomation;
import com.freely.data.network.responseEntities.RSGroupInfomation;
import com.freely.data.network.responseEntities.RSResult;
import com.freely.data.network.responseEntities.RSUserLocation;
import com.freely.ui.activities.MainActivity;
import com.freely.ui.util.ErrorUtil;
import com.freely.ui.util.ImageUtil;
import com.freely.ui.viewModel.GroupChatMapViewModel;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.zip.Inflater;

import androidx.annotation.RequiresApi;
import androidx.lifecycle.LifecycleOwner;
import butterknife.BindView;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okio.ByteString;
import rx.Scheduler;

public class MapMarkerClickListener implements BaiduMap.OnMarkerClickListener {
    private static final String TAG = "MapMarkerClickListener";
    private BaiduMap baiduMap;
    private Context context;
    private GroupChatMapViewModel groupChatMapViewModel;
    private View view;
    private TextView addressText,phoneText;
    private long groupId;
    private Button bt;
    private LatLng l;
    private static int latitudeBtn =1,longtitude=2;
    public MapMarkerClickListener(View view,Context context,BaiduMap baiduMap,long groupId,GroupChatMapViewModel groupChatMapViewModel,
    LatLng latlng) {
        this.groupChatMapViewModel=groupChatMapViewModel;
        this.view=view;
        this.context=context;
        this.baiduMap=baiduMap;
        this.groupId=groupId;
        l=latlng;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("ResourceAsColor")
    @Override
    public boolean onMarkerClick(Marker marker) {
        //从marker中获取info信息
        Bundle bundle = marker.getExtraInfo();
        RSUserLocation rsUserLocation = (RSUserLocation) bundle.getSerializable("info");

        groupChatMapViewModel.loadMemberInfo(rsUserLocation.getUserId(),groupId);
        ImageView iv_img = view.findViewById(R.id.head_icon);

        TextView tv_name =view.findViewById(R.id.user_name);
        tv_name.setText(rsUserLocation.getUserName());
        BottomSheetBehavior behavior = BottomSheetBehavior.from(view);
        //addressText = view.findViewById(R.id.user_address);
        phoneText = view.findViewById(R.id.user_phone);
        bt = view.findViewById(R.id.btn_search);
        LatLng latLn = new LatLng(rsUserLocation.getLocationLatitude(),rsUserLocation.getLocationLongitude());
        bt.setTag(latLn);
        bt.setOnClickListener(this::startSearch);
        getAddress(rsUserLocation.getLocationLatitude(),rsUserLocation.getLocationLongitude());
        setPhone();

        Glide.with(context)
                .load(ByteString.decodeBase64(rsUserLocation.getUserImage()).toByteArray())
                .apply(RequestOptions.circleCropTransform())
                .into(iv_img);

        Log.e(TAG, "onMarkerClick: "+rsUserLocation.getUserName());


        View view = View.inflate(context,R.layout.info_window,null);
        TextView name = view.findViewById(R.id.user_name_tv);
        ImageView iv = view.findViewById(R.id.icon_iv);
        addressText = view.findViewById(R.id.address_tv);

        getAddress(rsUserLocation.getLocationLatitude(),rsUserLocation.getLocationLongitude());
        name.setText(rsUserLocation.getUserName());
        Glide.with(context)
                .load(ByteString.decodeBase64(rsUserLocation.getUserImage()).toByteArray())
                .apply(RequestOptions.circleCropTransform())
                .into(iv);
    /*   TextView tv =new TextView(context);
       tv.setTextColor(Color.BLACK);
        tv.setText(rsUserLocation.getUserName());
        tv.setGravity(Gravity.CENTER);
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(tv);*/


        //infowindow位置
        LatLng latLng = new LatLng(rsUserLocation.getLocationLatitude(), rsUserLocation.getLocationLongitude());
        //infowindow点击事件
        InfoWindow.OnInfoWindowClickListener listener = new InfoWindow.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick() {
                //behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        };
        //显示infowindow
        InfoWindow infoWindow = new InfoWindow(view, latLng ,-10);
        baiduMap.showInfoWindow(infoWindow);
        return true;
    }

    private void startSearch(View view) {
        LatLng latLng  = (LatLng) view.getTag();
        Log.e(TAG, "startSearch: "+latLng.latitude+"aaa"+latLng.longitude );
        startSearch(latLng.latitude,latLng.longitude);
    }

    public void getAddress(double latitude, double longtitude){
        GeoCoder geoCoder=GeoCoder.newInstance();
        Log.e(TAG, "altitude: " +latitude+"longtitude"+longtitude);
        OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
            public void onGetGeoCodeResult(GeoCodeResult result) {

                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                    return;
                }

                //获取地理编码结果
            }
            @Override

            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {

                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    addressText.setText("无法通过经纬度转换成地址");
                    return;
                }
                ReverseGeoCodeResult.AddressComponent addressComponent=result.getAddressDetail();

                String s  = addressComponent.province + addressComponent.city+addressComponent.district+addressComponent.street+addressComponent.streetNumber;

                Log.e(TAG, "onGetReverseGeoCodeResult: "+s );
                if (!s.equals(""))
                addressText.setText(s);
                else
                    addressText.setText("该位置太过诡异，无法定位");

                geoCoder.destroy();
            }
        };
        LatLng latLng = new LatLng(latitude,longtitude);
        geoCoder.setOnGetGeoCodeResultListener(listener);
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
    }

    public void setPhone(){
        groupChatMapViewModel.getUserInfo().observe((LifecycleOwner) context, rsUserInfomation -> {
            Log.e(TAG, "setPhone: "+rsUserInfomation.getUserPhone() );
            phoneText.setText(rsUserInfomation.getUserPhone());
        });
    }

    public void startSearch(double latitude,double longtitude){
        RoutePlanSearch mSearch = RoutePlanSearch.newInstance();

        OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {

            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            public void onGetDrivingRouteResult(DrivingRouteResult result) {
                Log.e(TAG, "onGetDrivingRouteResult: "+result.getRouteLines().get(0).toString() );
                //获取驾车线路规划结果
            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }
        };

        mSearch.setOnGetRoutePlanResultListener(listener);

        PlanNode stNode = PlanNode.withLocation(l);
        LatLng latLng  =new LatLng(latitude,longtitude);
        PlanNode enNode = PlanNode.withLocation(latLng);
        mSearch.drivingSearch((new DrivingRoutePlanOption())
                .from(stNode)
                .to(enNode));
    }

}
